package com.gomoku.controller;

import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.application.Platform;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundImage;
import javafx.scene.layout.BackgroundPosition;
import javafx.scene.layout.BackgroundRepeat;
import javafx.scene.layout.BackgroundSize;
import java.net.URL;

public class StartController {
    // FXML注入的UI组件
    @FXML private AnchorPane startView_anchor;
    @FXML private Button singlePlayerBtn;
    @FXML private Button twoPlayerBtn;
    @FXML private Button Challenge_modeBtn;
    @FXML private Button Learning_modeBtn;
    @FXML private Button exitBtn;
    @FXML private Button settingsBtn;
    @FXML private ImageView settingsIcon;

    // 资源路径常量
    private static final String BG_IMAGE_PATH = "/com/gomoku/images/background.png";
    private static final String SETTINGS_ICON_PATH = "/com/gomoku/images/gear.jpg";

    @FXML
    private void initialize() {
        try {
            // 预检查关键资源
            if (!SceneManager.checkResourceExists(BG_IMAGE_PATH)) {
                throw new RuntimeException("背景图片资源缺失");
            }
            if (!SceneManager.checkResourceExists(SETTINGS_ICON_PATH)) {
                throw new RuntimeException("设置图标资源缺失");
            }

            // 初始化流程
            setBackgroundImage();
            loadSettingsIcon();
            setupButtonActions();

            System.out.println("启动界面初始化完成");

        } catch (Exception e) {
            showErrorAlert("初始化错误",
                    "启动界面初始化失败: " + e.getMessage() + "\n" +
                            "将使用最小功能模式运行");

            // 确保至少能退出应用
            setupBasicButtonActions();
        }
    }

    private void setBackgroundImage() {
        try {
            URL bgUrl = getClass().getResource(BG_IMAGE_PATH);
            BackgroundImage backgroundImage = new BackgroundImage(
                    new Image(bgUrl.toExternalForm()),
                    BackgroundRepeat.NO_REPEAT,
                    BackgroundRepeat.NO_REPEAT,
                    BackgroundPosition.CENTER,
                    new BackgroundSize(100, 100, true, true, false, true)
            );
            startView_anchor.setBackground(new Background(backgroundImage));
        } catch (Exception e) {
            System.err.println("背景图片加载失败: " + e.getMessage());
            startView_anchor.setStyle("-fx-background-color: linear-gradient(to bottom, #2c3e50, #4ca1af);");
        }
    }

    private void loadSettingsIcon() {
        try {
            URL iconUrl = getClass().getResource(SETTINGS_ICON_PATH);
            Image iconImage = new Image(iconUrl.toExternalForm());
            settingsIcon.setImage(iconImage);
            settingsIcon.setPreserveRatio(true);
            settingsIcon.setFitWidth(32);
        } catch (Exception e) {
            System.err.println("设置图标加载失败: " + e.getMessage());
            settingsIcon.setVisible(false);
            settingsBtn.setDisable(true);
        }
    }

    private void setupButtonActions() {
        // 统一按钮样式
        String buttonStyle = "-fx-font-size: 16px; -fx-min-width: 120px; -fx-min-height: 40px; "
                + "-fx-background-radius: 5px; -fx-text-fill: white; "
                + "-fx-background-color: #3498db; -fx-effect: dropshadow(gaussian, rgba(0,0,0,0.2), 5, 0, 0, 1);";

        singlePlayerBtn.setStyle(buttonStyle);
        twoPlayerBtn.setStyle(buttonStyle);
        Challenge_modeBtn.setStyle(buttonStyle);
        Learning_modeBtn.setStyle(buttonStyle);
        settingsBtn.setStyle(buttonStyle);
        exitBtn.setStyle(buttonStyle + "-fx-background-color: #e74c3c;");

        // 按钮事件绑定
        singlePlayerBtn.setOnAction(e -> switchToGameView("单人模式"));
        twoPlayerBtn.setOnAction(e -> switchToGameView("双人模式"));
        Challenge_modeBtn.setOnAction(e -> switchToGameView("闯关模式"));
        Learning_modeBtn.setOnAction(e -> switchToGameView("学习模式"));
        settingsBtn.setOnAction(e -> showSettings());
        exitBtn.setOnAction(e -> exitApplication());
    }

    private void setupBasicButtonActions() {
        // 最小功能保障
        exitBtn.setOnAction(e -> exitApplication());
    }

    private void switchToGameView(String mode) {
        System.out.println("正在切换到: " + mode);
        try {
            // 预检查游戏界面资源
            if (!SceneManager.checkResourceExists("/com/gomoku/view/GameView.fxml")) {
                throw new RuntimeException("游戏界面文件缺失");
            }
            SceneManager.loadScene("GameView");
        } catch (Exception e) {
            showErrorAlert("场景切换失败",
                    "无法加载游戏界面: " + e.getMessage() + "\n" +
                            "请检查游戏文件是否完整");
        }
    }

    private void showSettings() {
        Alert alert = new Alert(AlertType.INFORMATION);
        alert.setTitle("游戏设置");
        alert.setHeaderText("功能预览");
        alert.setContentText("设置功能将在后续版本中提供\n当前版本: 1.0.0");
        alert.showAndWait();
    }

    private void exitApplication() {
        System.out.println("正在安全退出应用...");
        Platform.exit();
        System.exit(0);
    }

    private void showErrorAlert(String title, String message) {
        Platform.runLater(() -> {
            Alert alert = new Alert(AlertType.ERROR);
            alert.setTitle(title);
            alert.setHeaderText(null);
            alert.setContentText(message);
            alert.showAndWait();
        });
    }
}